from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response

from rango.view.category import get_category_list
from rango.models import Page, Category
from datetime import datetime

def index(request):
    context = RequestContext(request)
    
    category_list =  Category.objects.order_by('-likes')[:5]
    
    context_dict = {
        'categories': category_list,
        'cat_list': get_category_list()
    }
    
    for category in category_list:
        category.url= category.id
        
    page_list = Page.objects.order_by('-views')[:5]
    context_dict['pages'] = page_list
        
    response = render_to_response('rango/index.html', context_dict, context)
    visits = int(request.COOKIES.get('visits','0'))
    
    if 'last_visit' in request.COOKIES:
        last_visit = request.COOKIES.get('last_visit')
        last_visit_time = datetime.strptime(last_visit[:-7], "%Y-%m-%d %H:%M:%S")

        if (datetime.now() - last_visit_time).seconds > 5:
            response.set_cookie('visits', visits + 1)
            response.set_cookie('last_visit', datetime.now())
    else:
        response.set_cookie('last_visit', datetime.now())
            
    return response